<template>
	<view class="articles-container">
		<!-- 顶部搜索栏 -->
		<view class="search-header">
			<view class="search-bar">
				<t-icon name="search" size="44rpx" color="#8cc9a1"></t-icon>
				<input 
					type="text" 
					placeholder="搜索健康文章" 
					v-model="keyword"
					confirm-type="search"
					@confirm="handleSearch"
				/>
				<t-icon v-if="keyword" name="close-circle" size="40rpx" color="#8cc9a1" @tap="clearSearch"></t-icon>
			</view>
		</view>
		
		<!-- 分类标签 -->
		<scroll-view scroll-x class="category-scroll" show-scrollbar="false" enhanced>
			<view class="category-list">
				<view 
					class="category-item" 
					:class="{ active: currentCategory === 'all' }"
					@tap="changeCategory('all')"
				>
					<text class="category-name">全部</text>
				</view>
				<view 
					class="category-item" 
					v-for="item in categories" 
					:key="item.id"
					:class="{ active: currentCategory === item.code }"
					@tap="changeCategory(item.code)"
				>
					<text class="category-name">{{ item.name }}</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 文章列表 -->
		<scroll-view 
			scroll-y 
			class="article-list-scroll" 
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
			refresher-background="#f5f7fa"
			@scroll="handleScroll"
		>
			<view class="article-list">
				<view v-if="loading && !refreshing" class="loading-container">
					<t-loading theme="dots" size="80rpx" text="加载中..." />
				</view>
				
				<view v-else-if="articles.length === 0" class="empty-container">
					<image src="/static/images/empty-state.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无相关文章</text>
					<button class="refresh-btn" @tap="refreshList">刷新试试</button>
				</view>
				
				<block v-else>
					<!-- 精选文章卡片 -->
					<view class="featured-article" v-if="featuredArticle && currentPage === 1">
						<image :src="featuredArticle.coverImage || '/static/images/placeholder.png'" class="featured-image" mode="aspectFill"></image>
						<view class="featured-overlay" @tap="viewArticle(featuredArticle)">
							<view class="featured-tag">精选</view>
							<view class="featured-info">
								<view class="featured-title">{{ featuredArticle.title }}</view>
								<view class="featured-meta">
									<view class="meta-item">
										<t-icon name="user" size="28rpx" color="#fff"></t-icon>
										<text>{{ featuredArticle.author }}</text>
									</view>
									<view class="meta-item">
										<t-icon name="browse" size="28rpx" color="#fff"></t-icon>
										<text>{{ featuredArticle.viewCount || 0 }} 阅读</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 普通文章列表 -->
					<view 
						class="article-card" 
						v-for="(item, index) in displayArticles" 
						:key="item.id"
						@tap="viewArticle(item)"
					>
						<image :src="item.coverImage || '/static/images/placeholder.png'" class="article-image" mode="aspectFill"></image>
						<view class="article-info">
							<view class="article-title">{{ item.title }}</view>
							<view class="article-summary">{{ item.summary }}</view>
							<view class="article-meta">
								<view class="meta-left">
									<view class="meta-item">
										<t-icon name="user" size="24rpx" color="#999"></t-icon>
										<text>{{ item.author }}</text>
									</view>
								</view>
								<view class="meta-right">
									<view class="meta-item">
										<t-icon name="browse" size="24rpx" color="#999"></t-icon>
										<text>{{ item.viewCount || 0 }}</text>
									</view>
									<view class="meta-item">
										<t-icon name="heart" size="24rpx" color="#999"></t-icon>
										<text>{{ item.likeCount || 0 }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 加载更多状态 -->
					<view class="list-status" v-if="articles.length > 0">
						<t-loading v-if="loadingMore" theme="circular" size="60rpx" text="加载更多..." />
						<text v-else-if="!hasMore" class="no-more">没有更多文章了</text>
					</view>
				</block>
			</view>
		</scroll-view>
		
		<!-- 回到顶部按钮 -->
		<view class="back-to-top" v-if="showBackToTop" @tap="scrollToTop">
			<t-icon name="arrow-up" size="40rpx" color="#fff"></t-icon>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted, watch, onBeforeMount } from 'vue'
	import { getArticleList, getArticleCategories } from '@/common/api/article.js'
	import { onPageScroll as usePageScroll } from '@dcloudio/uni-app'
	
	// 文章列表
	const articles = ref([])
	// 文章分类
	const categories = ref([])
	// 当前选中的分类
	const currentCategory = ref('all')
	// 搜索关键词
	const keyword = ref('')
	// 加载状态
	const loading = ref(false)
	const loadingMore = ref(false)
	const refreshing = ref(false)
	// 分页参数
	const currentPage = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const hasMore = ref(true)
	// 回到顶部按钮
	const showBackToTop = ref(false)
	
	// 计算精选文章（第一篇）
	const featuredArticle = computed(() => {
		return articles.value.length > 0 ? articles.value[0] : null
	})
	
	// 计算显示的文章列表（除了精选文章）
	const displayArticles = computed(() => {
		if (currentPage.value === 1 && articles.value.length > 0) {
			return articles.value.slice(1)
		}
		return articles.value
	})
	
	// 加载文章分类
	const loadCategories = async () => {
		try {
			console.log('开始加载文章分类')
			const res = await getArticleCategories()
			console.log('分类加载结果:', res)
			if (res.code === 0) {
				categories.value = res.data.map(category => {
					// 确保每个分类都有code属性
					if (!category.code && category.id) {
						// 如果没有code但有id，使用id作为code
						return {
							...category,
							code: category.code || String(category.id)
						}
					}
					return category
				})
				console.log('分类加载成功，数量:', categories.value.length)
				console.log('分类数据:', categories.value)
			}
		} catch (e) {
			console.error('加载文章分类失败:', e)
			uni.showToast({
				title: '加载分类失败',
				icon: 'none'
			})
		}
	}
	
	// 加载文章列表
	const loadArticles = async (isRefresh = true) => {
		if (isRefresh) {
			loading.value = true
			currentPage.value = 1
		} else {
			loadingMore.value = true
		}
		
		try {
			const params = {
				page: currentPage.value,
				pageSize: pageSize.value,
				keyword: keyword.value
			}
			
			// 只有当选择了具体分类时才添加category参数
			if (currentCategory.value !== 'all') {
				params.category = currentCategory.value
			}
			
			console.log('请求文章列表参数:', params)
			const res = await getArticleList(params)
			console.log('文章列表响应:', res)
			
			if (res.code === 0) {
				const { list, total: totalCount } = res.data
				
				if (!list || !Array.isArray(list)) {
					console.error('API返回的列表格式不正确:', list)
					throw new Error('数据格式错误')
				}
				
				// 如果是加载更多，拼接数据；如果是刷新，替换数据
				if (isRefresh) {
					articles.value = list
				} else {
					articles.value = [...articles.value, ...list]
				}
				
				total.value = totalCount
				hasMore.value = articles.value.length < totalCount
				
				console.log('加载的文章数量:', list.length)
				console.log('文章总数:', totalCount)
				console.log('当前文章列表长度:', articles.value.length)
			} else {
				throw new Error(res.message || '加载失败')
			}
		} catch (e) {
			console.error('加载文章列表失败:', e)
			uni.showToast({
				title: '加载文章失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
			loadingMore.value = false
			refreshing.value = false
		}
	}
	
	// 切换分类
	const changeCategory = (categoryId) => {
		if (currentCategory.value === categoryId) return
		
		console.log('切换分类:', categoryId)
		currentCategory.value = categoryId
		loadArticles(true)
	}
	
	// 处理搜索
	const handleSearch = () => {
		loadArticles(true)
	}
	
	// 清除搜索
	const clearSearch = () => {
		keyword.value = ''
		loadArticles(true)
	}
	
	// 刷新列表
	const refreshList = () => {
		loadArticles(true)
	}
	
	// 下拉刷新
	const onRefresh = () => {
		refreshing.value = true
		loadArticles(true)
	}
	
	// 查看文章详情
	const viewArticle = (article) => {
		uni.navigateTo({
			url: `/pages/articles/detail?id=${article.id}`
		})
	}
	
	// 加载更多
	const loadMore = () => {
		if (loading.value || loadingMore.value || !hasMore.value) return
		
		currentPage.value++
		loadArticles(false)
	}
	
	// 滚动到顶部
	const scrollToTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		})
	}
	
	// 处理滚动事件
	const handleScroll = (e) => {
		showBackToTop.value = e.detail.scrollTop > 300
	}
	
	// 使用正确的页面滚动监听方法
	usePageScroll(({scrollTop}) => {
		showBackToTop.value = scrollTop > 300
	})
	
	// 监听关键词变化，当清空关键词时自动刷新列表
	watch(keyword, (newVal, oldVal) => {
		if (oldVal && !newVal) {
			loadArticles(true)
		}
	})
	
	// 页面加载
	onMounted(() => {
		console.log('文章列表页面加载')
		// 初始化页面数据
		loadCategories()
		// 延迟一下加载文章，确保分类已加载
		setTimeout(() => {
			console.log('开始加载所有文章，当前分类:', currentCategory.value)
			loadArticles(true)
		}, 300)
	})
</script>

<style lang="scss">
	.articles-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
		
		.search-header {
			background-color: #fff;
			padding: 30rpx;
			position: relative;
			z-index: 10;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			
			.search-bar {
				background-color: #f5f7fa;
				border-radius: 40rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				padding: 0 30rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03) inset;
				
				input {
					flex: 1;
					height: 100%;
					font-size: 28rpx;
					margin: 0 20rpx;
				}
			}
		}
		
		.category-scroll {
			background-color: #fff;
			white-space: nowrap;
			padding: 0 20rpx 20rpx;
			
			.category-list {
				display: inline-flex;
				padding: 10rpx 0;
				
				.category-item {
					padding: 12rpx 30rpx;
					margin-right: 20rpx;
					border-radius: 30rpx;
					background-color: #f5f7fa;
					transition: all 0.3s;
					
					&.active {
						background-color: #8cc9a1;
						box-shadow: 0 4rpx 12rpx rgba(140, 201, 161, 0.3);
						
						.category-name {
							color: #fff;
							font-weight: 500;
						}
					}
					
					.category-name {
						font-size: 28rpx;
						color: #666;
					}
				}
			}
		}
		
		.article-list-scroll {
			flex: 1;
			width: 100%;
		}
		
		.article-list {
			padding: 20rpx;
			
			.featured-article {
				position: relative;
				margin-bottom: 30rpx;
				border-radius: 20rpx;
				overflow: hidden;
				box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
				
				.featured-image {
					width: 100%;
					height: 380rpx;
					display: block;
				}
				
				.featured-overlay {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: linear-gradient(to bottom, rgba(0,0,0,0) 30%, rgba(0,0,0,0.7) 100%);
					padding: 30rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					
					.featured-tag {
						align-self: flex-start;
						background-color: #8cc9a1;
						color: #fff;
						font-size: 24rpx;
						padding: 6rpx 20rpx;
						border-radius: 20rpx;
						font-weight: 500;
						box-shadow: 0 2rpx 8rpx rgba(140, 201, 161, 0.3);
					}
					
					.featured-info {
						.featured-title {
							font-size: 36rpx;
							color: #fff;
							font-weight: bold;
							margin-bottom: 20rpx;
							text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.3);
							
							// 最多显示两行
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
							overflow: hidden;
						}
						
						.featured-meta {
							display: flex;
							align-items: center;
							
							.meta-item {
								display: flex;
								align-items: center;
								margin-right: 30rpx;
								
								text {
									font-size: 24rpx;
									color: #fff;
									margin-left: 8rpx;
								}
							}
						}
					}
				}
			}
			
			.article-card {
				display: flex;
				flex-direction: column;
				background-color: #fff;
				border-radius: 20rpx;
				overflow: hidden;
				margin-bottom: 30rpx;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
				transform: translateY(0);
				transition: transform 0.3s, box-shadow 0.3s;
				
				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
				}
				
				.article-image {
					width: 100%;
					height: 240rpx;
					display: block;
				}
				
				.article-info {
					padding: 24rpx;
					
					.article-title {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 16rpx;
						line-height: 1.4;
						
						// 最多显示两行
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}
					
					.article-summary {
						font-size: 28rpx;
						color: #666;
						line-height: 1.5;
						margin-bottom: 20rpx;
						
						// 最多显示两行
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}
					
					.article-meta {
						display: flex;
						justify-content: space-between;
						align-items: center;
						
						.meta-left, .meta-right {
							display: flex;
							align-items: center;
						}
						
						.meta-item {
							display: flex;
							align-items: center;
							margin-right: 20rpx;
							
							&:last-child {
								margin-right: 0;
							}
							
							text {
								font-size: 24rpx;
								color: #999;
								margin-left: 6rpx;
							}
						}
					}
				}
			}
		}
		
		.loading-container, .empty-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 0;
			
			.empty-image {
				width: 240rpx;
				height: 240rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 30rpx;
			}
			
			.refresh-btn {
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				padding: 12rpx 40rpx;
				border-radius: 40rpx;
			}
		}
		
		.list-status {
			padding: 30rpx 0;
			text-align: center;
			
			.no-more {
				font-size: 26rpx;
				color: #999;
			}
		}
		
		.back-to-top {
			position: fixed;
			right: 30rpx;
			bottom: 120rpx;
			width: 80rpx;
			height: 80rpx;
			background-color: #8cc9a1;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0 4rpx 16rpx rgba(140, 201, 161, 0.4);
			z-index: 100;
			opacity: 0.9;
			transition: opacity 0.3s;
			
			&:active {
				opacity: 1;
			}
		}
	}
</style> 